package com.xuecheng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.mapper.TeachplanMapper;
import com.xuecheng.mapper.TeachplanMediaMapper;
import com.xuecheng.model.dto.BindTeachplanMediaDto;
import com.xuecheng.model.po.Teachplan;
import com.xuecheng.model.po.TeachplanMedia;
import com.xuecheng.service.TeachplanMediaService;
import com.xuecheng.service.TeachplanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-04-15
 */
@Service
public class TeachplanMediaServiceImpl extends ServiceImpl<TeachplanMediaMapper, TeachplanMedia> implements TeachplanMediaService {

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;


    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //构造查询条件
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, bindTeachplanMediaDto.getTeachplanId());
        //查询该条数据是否存在
        TeachplanMedia teachplanMedia = teachplanMediaMapper.selectOne(queryWrapper);
        //如果不等于空则更新
        if (teachplanMedia != null){
            teachplanMedia = new TeachplanMedia();
            teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
            teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
            int update = teachplanMediaMapper.update(teachplanMedia, queryWrapper);
            return update <= 0 ? null:teachplanMedia;
        }
        //插入数据
        teachplanMedia = new TeachplanMedia();
        Teachplan teachplan = teachplanMapper.selectById(bindTeachplanMediaDto.getTeachplanId());//拿到课程标识
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setTeachplanId(bindTeachplanMediaDto.getTeachplanId());
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        int insert = teachplanMediaMapper.insert(teachplanMedia);
        return insert <= 0 ? null:teachplanMedia;
    }

    /**
     * 删除章节关联视频信息
     * @param courseID 课程ID
     * @param MediaID 视频ID
     * @return
     */
    @Override
    public Boolean DeleteCourseVideoMessage(long courseID, String MediaID) {
        LambdaQueryWrapper<TeachplanMedia> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TeachplanMedia::getTeachplanId , courseID);
        wrapper.eq(TeachplanMedia::getMediaId , MediaID);
        int delete = teachplanMediaMapper.delete(wrapper);
        return delete <= 0 ? false:true;
    }

}
